package com.sgcc.ln.pmos.mobileapp.activity;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.os.Handler;
import android.os.Message;
import android.view.View;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.DefaultItemAnimator;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.alibaba.android.arouter.facade.annotation.Route;
import com.blankj.utilcode.util.ToastUtils;
import com.sgcc.ln.pmos.arouter.app.AppArouterPath;
import com.sgcc.ln.pmos.common.base.BasePresenter;
import com.sgcc.ln.pmos.common.base.MvpBaseActivity;
import com.sgcc.ln.pmos.common.listener.OnItemClickListener;
import com.sgcc.ln.pmos.common.utils.XXPermissionsUtil;
import com.sgcc.ln.pmos.common.widget.TitleBar;
import com.sgcc.pmos.nativesdk.R;
import com.sgcc.ln.pmos.mobileapp.adapter.ChooseFileAdapter;
import com.sgcc.ln.pmos.mobileapp.bean.FileInfo;

import java.io.File;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

@Route(path = AppArouterPath.APP_CHOOSEFILE)
public class ChooseFileActivity extends MvpBaseActivity {

    private TitleBar mTitleBar;
    private RecyclerView mRvContent;

    private ChooseFileAdapter mChooseFileAdapter;
    private List<FileInfo> fileList = new ArrayList<>(),
            fileList1 = new ArrayList<>(),
            fileList2 = new ArrayList<>(),
            fileList3 = new ArrayList<>(),
            fileList4 = new ArrayList<>(),
            fileListTotal = new ArrayList<>();
    private volatile boolean result1 = false, result2 = false, result3 = false, result4 = false, result5 = false;
    private List<String> pathList = new ArrayList<>();
    private Thread thread1, thread2, thread3, thread4, thread5;
    private ExecutorService pool;

    @Override
    protected int getContentViewLayoutID() {
        return R.layout.activity_choosefile;
    }

    @Override
    protected BasePresenter createPresenter() {
        return null;
    }

    @Override
    protected void initViews() {
        super.initViews();
        mTitleBar = (TitleBar) findViewById(R.id.title_bar);
        mRvContent = (RecyclerView) findViewById(R.id.rv_content);
        mTitleBar.setTitle("选择文件");
        mTitleBar.setRightIcon(R.mipmap.go_main, new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                goMainActivity();
            }
        });

        pool = Executors.newFixedThreadPool(5);
        LinearLayoutManager mLayoutManager = new LinearLayoutManager(this, LinearLayoutManager.VERTICAL, false);
        mRvContent.setLayoutManager(mLayoutManager);
        mRvContent.setItemAnimator(new DefaultItemAnimator());
        mChooseFileAdapter = new ChooseFileAdapter(this);
        mRvContent.setAdapter(mChooseFileAdapter);

        mChooseFileAdapter.setOnItemClickListener(new OnItemClickListener() {
            @Override
            public void onItemClick(Object bean, int position) {
                FileInfo file = (FileInfo) bean;
                if (file.getLength() >= 1024 * 1024 * 20) {
                    ToastUtils.showShort("选择文件过大，请选择小于20M文件重试");
                    return;
                }
                Intent intent = new Intent();
                intent.putExtra("FileName", file.getName());
                intent.putExtra("FilePath", file.getPath());
                intent.putExtra("FileSize", file.getLength());
                setResult(2222, intent);
                finish();

            }
        });


    }

    @Override
    protected void initData() {
        showLoading();
        thread1 = new Thread(new Runnable() {
            @Override
            public void run() {
                refreshFileList(fileList, "/sdcard/tencent");
                if (Thread.currentThread().isInterrupted()) return;
                result1 = true;
                handler.sendEmptyMessage(1);
            }
        });
        thread2 = new Thread(new Runnable() {
            @Override
            public void run() {
                refreshFileList(fileList1, "/sdcard/Download");
                if (Thread.currentThread().isInterrupted()) return;
                result2 = true;
                handler.sendEmptyMessage(1);
            }
        });
        thread3 = new Thread(new Runnable() {
            @Override
            public void run() {
                refreshFileList(fileList2, "/sdcard/DingTalk");
                if (Thread.currentThread().isInterrupted()) return;
                result3 = true;
                handler.sendEmptyMessage(1);
            }
        });
        thread4 = new Thread(new Runnable() {
            @Override
            public void run() {
                refreshFileList(fileList3, "/sdcard/QQBrowser");
                if (Thread.currentThread().isInterrupted()) return;
                result4 = true;
                handler.sendEmptyMessage(1);
            }
        });
        thread5 = new Thread(new Runnable() {
            @Override
            public void run() {
                refreshFileList(fileList4, "/storage/emulated/0/");
                if (Thread.currentThread().isInterrupted()) return;
                result5 = true;
                handler.sendEmptyMessage(1);
            }
        });

        XXPermissionsUtil.externalStorage(ChooseFileActivity.this, new XXPermissionsUtil.PermissionCallback() {
            @Override
            public void Call() {
                pool.execute(thread1);
                pool.execute(thread2);
                pool.execute(thread3);
                pool.execute(thread4);
                pool.execute(thread5);
            }
        });
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        thread1.interrupt();
        thread2.interrupt();
        thread3.interrupt();
        thread4.interrupt();
        thread5.interrupt();
        thread1 = null;
        thread2 = null;
        thread3 = null;
        thread4 = null;
        thread5 = null;
        pool.shutdown();
        handler.removeMessages(1);
    }

    @SuppressLint("HandlerLeak")
    private Handler handler = new Handler() {
        @Override
        public void handleMessage(@NonNull Message msg) {
            super.handleMessage(msg);
            if (result1 && result2 && result3 && result4 && result5) {
                fileListTotal.clear();
                fileListTotal.addAll(fileList);
                fileListTotal.addAll(fileList1);
                fileListTotal.addAll(fileList2);
                fileListTotal.addAll(fileList3);
                fileListTotal.addAll(fileList4);
                dismissLoading();
                mChooseFileAdapter.setNotifyData(fileListTotal);
            }

        }
    };

    public static void refreshFileList(List<FileInfo> fileList, String strPath) {
        if (Thread.currentThread().isInterrupted()) return;

        String filename;
        File dir = new File(strPath);
        File[] files = dir.listFiles();

        if (files == null)
            return;

        for (int i = 0; i < files.length; i++) {
            if (Thread.currentThread().isInterrupted()) return;
            if (files[i].isDirectory()) {
                refreshFileList(fileList, files[i].getAbsolutePath());
            } else {
                filename = files[i].getName();
                // 获取后缀名前的分隔符"."在fName中的位置。
                int dotIndex = filename.lastIndexOf(".");
                if (dotIndex > 0) {
                    String end = filename.substring(dotIndex);
                    if (".pdf".equalsIgnoreCase(end) || "pdf".equalsIgnoreCase(end) || ".doc".equalsIgnoreCase(end) || ".docx".equalsIgnoreCase(end)) {
                        FileInfo info = new FileInfo();
                        info.setName(files[i].getName());
                        info.setPath(files[i].getPath());
                        info.setLastModified(files[i].lastModified());
                        info.setLength(files[i].length());
                        fileList.add(info);
                    }
                }
            }
        }
    }
}
